package littlecyberwar.tool;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.util.*;

import littlecyberwar.model.*;
import littlecyberwar.ui.*;
import littlecyberwar.util.*;

/**
 * <p>
 * This placement handler is slightly different from other mouse handler in the
 * following ways:
 * <p>1. startAction is trigger when a unit is selected from a Tray. In which
 * case the setUnit() call will be made.
 * <p>2. Once there's a unit selected, then the mouseDragged
 * will trigger a selected Rectangle to be displayed.
 * <p>3. A mouse release will place the unit on the board, with the unit facing
 * the 12 o'clock direction.
 */
public class MousePlacementHandler extends MouseHandler {
  

  public MousePlacementHandler() {
    super();
    id = H_PLACEMENT;
	unitSelectedText = "Drag mouse anywhere place on board and release button to place unit.";
	noUnitSelectedText = "Click on a unit in a tray to be placed onto the board.";
  }
  
  public void setElement(Element el) {
    // System.out.println("Enter setElement for " + this.toString());
    currEl = el;
    Shape transR = el.getFinalShape();
    selectedRectangle = transR;
    originalRec = el.getRectangle();
    selectedTrans = el.getTransform();
    currTrans = (AffineTransform)selectedTrans.clone();
  }

  /**
   * This is called when the mouse is down, need to startAction
   */
  public boolean checkSelection( MouseEvent e ) {
    startAction(e);
    return ( false );
  }

  public void startAction( MouseEvent e ) {
    /**
     * It's the same logic when clicked on board as dragging
     */
    super.startAction(e);
    mouseDragged(e);
  }

  /**
   * Overrides superclass impl.
   * In placement case set selected rectangle to null as soon as
   * mouse is released.
   */
  public UnitCommand mouseUp(MouseEvent e) {
  	UnitCommand cmd=null;
    if ( (selectedRectangle != null ) && (currEl != null)) {
		Tray t = (Tray)Util.lookup.get(Util._CURR_SELECTED_TRAY);
		cmd = new UnitCommandPlacement(currEl.getElementId(), id, currTrans, t.getId());
		cmd.setPlayerName(Players.getSelfName());
		resetSelectedElement();
    }
	return ( cmd );
  }

  protected void dragSelected( Point newP ) {

    currTrans.setToTranslation(newP.getX(), newP.getY());
    selectedRectangle = currTrans.createTransformedShape(originalRec);
    return;
  }

  /**
   * Override setmodel here
   * In this case there already maybe a selected unit in the tray
   * If a selected unit exist from the tray, need to set it as selected
   * Unit.
   */
  public void setModelFacade(InternalCmdFacade m) {
    super.setModelFacade(m);
    Element el = (Element)Util.lookup.get(Util._EL_SELECTED_FROM_TRAY);
    if ( el != null ) {
      setElement( el );
    } else {
    	Debug.out("why is element=null from Util._EL_SELECTED_FROM_TRAY?");
    }
    return;
  }

}